package net.zigin.nhi.waste.view.collect;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.gyf.immersionbar.ImmersionBar;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.olc.uhf.tech.ISO1800_6C;
import com.olc.uhf.tech.IUhfCallback;
import com.tbruyelle.rxpermissions2.RxPermissions;

import net.zigin.nhi.waste.MainApplication;
import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.maghuf.DevBeep;
import net.zigin.nhi.waste.utils.CommonUtils;
import net.zigin.nhi.waste.utils.JsonParser;
import net.zigin.nhi.waste.utils.GravityUnitUtils;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.view.ble.BleSearchActivity;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.paperdb.Paper;


/**
 * 医废收集界面
 */
public class WasteCollectActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout mConnectState;
    private ImageView mImgConnect;
    private TextView mTvConnect;
    private EditText mTvGravity;
    private EditText mRemark;
    private LinearLayout mInfectLayout;
    private ImageView mInfectImg;
    private TextView mInfectTv;
    private LinearLayout mDamageLayout;
    private ImageView mDamageImg;
    private TextView mDamageTv;
    private LinearLayout mPathoLayout;
    private ImageView mPathoImg;
    private TextView mPathoTv;
    private LinearLayout mDrugLayout;
    private ImageView mDrugImg;
    private TextView mDrugTv;
    private LinearLayout mChemistryLayout;
    private ImageView mChemistryImg;
    private TextView mChemistryTv;
    private EditText mRfidCode;

    private String uuid_service;
    private String uuid_character;
    private String gravity;
    private final Map<String, Object> collectMap = new HashMap<>();

    // 语音听写对象
    private SpeechRecognizer mIat;
    // 语音听写UI
    private RecognizerDialog mIatDialog;

    private ISO1800_6C uhf_6c;
    private Handler mHandler = new MyHandler();
    private boolean isLoop = false;
    Set<String> epcSet = new HashSet<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waste_collect);
        initView();

        if (MainApplication.mService != null) {
            uhf_6c = MainApplication.mService.getISO1800_6C();
            DevBeep.init(WasteCollectActivity.this);
        }

        // 初始化识别无UI识别对象
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
        // 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mIatDialog = new RecognizerDialog(this, mInitListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        uuid_service = Paper.book().read(Constants.UUID_SERVICE);
        uuid_character = Paper.book().read(Constants.UUID_CHARACTER);
        BleManager.getInstance().enableBluetooth();
        connectBle();

        mTvGravity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mTvGravity.getText().toString().contains(".")) {
                    if (mTvGravity.getText().toString().indexOf(".", mTvGravity.getText().toString().indexOf(".") + 1) > 0) {
                        Toast.makeText(getApplicationContext(), "已经输入\".\"不能重复输入", Toast.LENGTH_SHORT).show();
                        mTvGravity.setText(mTvGravity.getText().toString().substring(0, mTvGravity.getText().toString().length() - 1));
                        mTvGravity.setSelection(mTvGravity.getText().toString().length());
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mConnectState = findViewById(R.id.connect_state);
        mImgConnect = findViewById(R.id.img_connect);
        mTvConnect = findViewById(R.id.tv_connect);
        mTvGravity = findViewById(R.id.tv_gravity);
        mRfidCode = findViewById(R.id.rfid_code);
        Button mRead = findViewById(R.id.read);
        Button mReRead = findViewById(R.id.reRead);
        mInfectLayout = findViewById(R.id.infect_layout);
        mInfectImg = findViewById(R.id.infect_img);
        mInfectTv = findViewById(R.id.infect_tv);
        mDamageLayout = findViewById(R.id.damage_layout);
        mDamageImg = findViewById(R.id.damage_img);
        mDamageTv = findViewById(R.id.damage_tv);
        mPathoLayout = findViewById(R.id.patho_layout);
        mPathoImg = findViewById(R.id.patho_img);
        mPathoTv = findViewById(R.id.patho_tv);
        mDrugLayout = findViewById(R.id.drug_layout);
        mDrugImg = findViewById(R.id.drug_img);
        mDrugTv = findViewById(R.id.drug_tv);
        mChemistryLayout = findViewById(R.id.chemistry_layout);
        mChemistryImg = findViewById(R.id.chemistry_img);
        mChemistryTv = findViewById(R.id.chemistry_tv);
        Button mBtnSpeech = findViewById(R.id.btnSpeech);
        mRemark = findViewById(R.id.remark);
        Button mPost = findViewById(R.id.post);

        mConnectState.setOnClickListener(this);
        mInfectLayout.setOnClickListener(this);
        mDamageLayout.setOnClickListener(this);
        mPathoLayout.setOnClickListener(this);
        mDrugLayout.setOnClickListener(this);
        mChemistryLayout.setOnClickListener(this);
        mReRead.setOnClickListener(this);
        mRead.setOnClickListener(this);
        mBtnSpeech.setOnClickListener(this);
        mPost.setOnClickListener(this);
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = code -> {
        Log.d("语音听写", "SpeechRecognizer init() code = " + code);
        if (code != ErrorCode.SUCCESS) {
            Toast.makeText(WasteCollectActivity.this, "语音听写初始化失败", Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {
            Log.d("语音听写", "recognizer result：" + results.getResultString());

            String text = JsonParser.parseIatResult(results.getResultString());
            mRemark.append(text);
            mRemark.setSelection(mRemark.length());
        }

        /**
         * 识别回调错误.
         */
        public void onError(SpeechError error) {
            Toast.makeText(WasteCollectActivity.this, error.getPlainDescription(true), Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 参数设置
     */
    public void setParam() {
        // 清空参数
//        mIat.setParameter(SpeechConstant.PARAMS, null);
        String lag = "en_us";
        // 设置引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, "cloud");
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
        mIat.setParameter(SpeechConstant.ACCENT, null);
        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        // 设置语言区域
        mIat.setParameter(SpeechConstant.ACCENT, lag);
        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, "4000");

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, "1000");

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT,  "1");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,
                getExternalFilesDir("msc").getAbsolutePath() + "/iat.wav");
    }

    /**
     * 每次进此界面, 如果此时没有连接中的蓝牙，自动去连接数据库中记录的连接过的蓝牙设备
     */
    private void connectBle() {
        if (!Constants.BLE_CONNECT_STATE) {
            mConnectState.setBackgroundColor(Color.parseColor("#F0E2E0"));
            mImgConnect.setImageResource(R.drawable.img_connect_fail);
            mTvConnect.setText("蓝牙称连接失败，请重新连接");
            mTvConnect.setTextColor(Color.parseColor("#F4664A"));

            Set<String> macSet = Paper.book().read(Constants.BLEMACS);
            //判断数据库中是否存在已记录的MAC。有就直接连接，没有则显示未连接状态栏
            if (macSet != null && macSet.size() > 0) {
                for (String mac : macSet) {
                    BleManager.getInstance().connect(mac, new BleGattCallback() {
                        @Override
                        public void onStartConnect() {

                        }

                        @Override
                        public void onConnectFail(BleDevice bleDevice, BleException exception) {
                            Log.i("连接情况", "连接失败！");
                        }

                        @Override
                        public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                            Log.i("连接情况", "连接成功！");
                            Constants.BLEDEVICE = bleDevice;

                            List<BluetoothGattService> serviceList = gatt.getServices();
                            if (bleDevice.getName().contains("Furi")) {
                                uuid_service = serviceList.get(3).getUuid().toString();
                                uuid_character = serviceList.get(3).getCharacteristics().get(0).getUuid().toString();
                            }

                            if (bleDevice.getName().equals("HC-42")) {
                                if (serviceList.size() > 2) {
                                    uuid_service = serviceList.get(2).getUuid().toString();
                                    if (serviceList.get(2).getCharacteristics().size() > 0) {
                                        uuid_character = serviceList.get(2).getCharacteristics().get(0).getUuid().toString();
                                    }
                                }
                            }

                            runOnUiThread(() -> {
                                mConnectState.setBackgroundColor(Color.parseColor("#F2EAD7"));
                                mImgConnect.setImageResource(R.drawable.img_connect_success);
                                mTvConnect.setText("蓝牙称连接成功");
                                mTvConnect.setTextColor(Color.parseColor("#FFAA00"));
                            });

                        }

                        @Override
                        public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                            if (isActiveDisConnected) {
                                Log.i("连接情况", "断开连接");
                            }
                        }
                    });
                }
            }
        } else {
            mConnectState.setBackgroundColor(Color.parseColor("#F2EAD7"));
            mImgConnect.setImageResource(R.drawable.img_connect_success);
            mTvConnect.setText("蓝牙称连接成功");
            mTvConnect.setTextColor(Color.parseColor("#FFAA00"));
        }

    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        if(CommonUtils.isFastClick()){
            return;
        }
        switch (v.getId()) {
            case R.id.connect_state: //顶部连接状态栏
                Intent intent1 = new Intent(WasteCollectActivity.this, BleSearchActivity.class);
                startActivity(intent1);
                break;
            case R.id.reRead:   //重新读取按钮
                if (Constants.BLEDEVICE != null) {
                    receiveBleData();
                }
                new Handler().postDelayed(() -> {
                    BleManager.getInstance().stopNotify(Constants.BLEDEVICE, uuid_service, uuid_character);
                    GravityUnitUtils utils = new GravityUnitUtils();
                    mTvGravity.setText(utils.getGravity(WasteCollectActivity.this, gravity));
                }, 700);
                break;
            case R.id.infect_layout: //感染性
                collectMap.put("wasteClassifyName", "感染性");
                collectMap.put("wasteClassifyCode", "infection");
                mInfectLayout.setBackgroundResource(R.drawable.collect_bg_selected);
                mInfectImg.setImageResource(R.drawable.infectivity_selected);
                mInfectTv.setTextColor(Color.parseColor("#34BAFF"));

                mDamageLayout.setBackgroundResource(R.drawable.collect_bg);
                mDamageImg.setImageResource(R.drawable.damage);
                mDamageTv.setTextColor(Color.parseColor("#333333"));
                mPathoLayout.setBackgroundResource(R.drawable.collect_bg);
                mPathoImg.setImageResource(R.drawable.pathological);
                mPathoTv.setTextColor(Color.parseColor("#333333"));
                mDrugLayout.setBackgroundResource(R.drawable.collect_bg);
                mDrugImg.setImageResource(R.drawable.drug);
                mDrugTv.setTextColor(Color.parseColor("#333333"));
                mChemistryLayout.setBackgroundResource(R.drawable.collect_bg);
                mChemistryImg.setImageResource(R.drawable.chemistry);
                mChemistryTv.setTextColor(Color.parseColor("#333333"));
                break;
            case R.id.damage_layout: //损伤性
                collectMap.put("wasteClassifyName", "损伤性");
                collectMap.put("wasteClassifyCode", "injury");
                mDamageLayout.setBackgroundResource(R.drawable.collect_bg_selected);
                mDamageImg.setImageResource(R.drawable.damage_selected);
                mDamageTv.setTextColor(Color.parseColor("#34BAFF"));

                mInfectLayout.setBackgroundResource(R.drawable.collect_bg);
                mInfectImg.setImageResource(R.drawable.infectivity);
                mInfectTv.setTextColor(Color.parseColor("#333333"));
                mPathoLayout.setBackgroundResource(R.drawable.collect_bg);
                mPathoImg.setImageResource(R.drawable.pathological);
                mPathoTv.setTextColor(Color.parseColor("#333333"));
                mDrugLayout.setBackgroundResource(R.drawable.collect_bg);
                mDrugImg.setImageResource(R.drawable.drug);
                mDrugTv.setTextColor(Color.parseColor("#333333"));
                mChemistryLayout.setBackgroundResource(R.drawable.collect_bg);
                mChemistryImg.setImageResource(R.drawable.chemistry);
                mChemistryTv.setTextColor(Color.parseColor("#333333"));
                break;
            case R.id.patho_layout: //病理性
                collectMap.put("wasteClassifyName", "病理性");
                collectMap.put("wasteClassifyCode", "pathology");
                mPathoLayout.setBackgroundResource(R.drawable.collect_bg_selected);
                mPathoImg.setImageResource(R.drawable.pathological_selected);
                mPathoTv.setTextColor(Color.parseColor("#34BAFF"));

                mDamageLayout.setBackgroundResource(R.drawable.collect_bg);
                mDamageImg.setImageResource(R.drawable.damage);
                mDamageTv.setTextColor(Color.parseColor("#333333"));
                mInfectLayout.setBackgroundResource(R.drawable.collect_bg);
                mInfectImg.setImageResource(R.drawable.infectivity);
                mInfectTv.setTextColor(Color.parseColor("#333333"));
                mDrugLayout.setBackgroundResource(R.drawable.collect_bg);
                mDrugImg.setImageResource(R.drawable.drug);
                mDrugTv.setTextColor(Color.parseColor("#333333"));
                mChemistryLayout.setBackgroundResource(R.drawable.collect_bg);
                mChemistryImg.setImageResource(R.drawable.chemistry);
                mChemistryTv.setTextColor(Color.parseColor("#333333"));
                break;
            case R.id.drug_layout: //药物性
                collectMap.put("wasteClassifyName", "药物性");
                collectMap.put("wasteClassifyCode", "drug");
                mDrugLayout.setBackgroundResource(R.drawable.collect_bg_selected);
                mDrugImg.setImageResource(R.drawable.drug_selected);
                mDrugTv.setTextColor(Color.parseColor("#34BAFF"));

                mDamageLayout.setBackgroundResource(R.drawable.collect_bg);
                mDamageImg.setImageResource(R.drawable.damage);
                mDamageTv.setTextColor(Color.parseColor("#333333"));
                mPathoLayout.setBackgroundResource(R.drawable.collect_bg);
                mPathoImg.setImageResource(R.drawable.pathological);
                mPathoTv.setTextColor(Color.parseColor("#333333"));
                mInfectLayout.setBackgroundResource(R.drawable.collect_bg);
                mInfectImg.setImageResource(R.drawable.infectivity);
                mInfectTv.setTextColor(Color.parseColor("#333333"));
                mChemistryLayout.setBackgroundResource(R.drawable.collect_bg);
                mChemistryImg.setImageResource(R.drawable.chemistry);
                mChemistryTv.setTextColor(Color.parseColor("#333333"));
                break;
            case R.id.chemistry_layout: //化学性
                collectMap.put("wasteClassifyName", "化学性");
                collectMap.put("wasteClassifyCode", "chemical");
                mChemistryLayout.setBackgroundResource(R.drawable.collect_bg_selected);
                mChemistryImg.setImageResource(R.drawable.chemistry_selected);
                mChemistryTv.setTextColor(Color.parseColor("#34BAFF"));

                mDamageLayout.setBackgroundResource(R.drawable.collect_bg);
                mDamageImg.setImageResource(R.drawable.damage);
                mDamageTv.setTextColor(Color.parseColor("#333333"));
                mPathoLayout.setBackgroundResource(R.drawable.collect_bg);
                mPathoImg.setImageResource(R.drawable.pathological);
                mPathoTv.setTextColor(Color.parseColor("#333333"));
                mDrugLayout.setBackgroundResource(R.drawable.collect_bg);
                mDrugImg.setImageResource(R.drawable.drug);
                mDrugTv.setTextColor(Color.parseColor("#333333"));
                mInfectLayout.setBackgroundResource(R.drawable.collect_bg);
                mInfectImg.setImageResource(R.drawable.infectivity);
                mInfectTv.setTextColor(Color.parseColor("#333333"));
                break;
            case R.id.btnSpeech:  //语音按钮
                RxPermissions permissions = new RxPermissions(this);
                permissions.request(Manifest.permission.RECORD_AUDIO)
                        .subscribe(granted ->{
                            if (!granted) { //申请失败
                                Toast.makeText(this, "权限未开启, 将无法识别语音！", Toast.LENGTH_SHORT).show();
                            } else {
                                speechToText();
                            }
                        });
                break;
            case R.id.post:  //提交按钮
                if (StringUtil.isEmpty((String) collectMap.get("wasteClassifyName"))) {
                    Toast.makeText(this, "请选择医废类型！", Toast.LENGTH_SHORT).show();
                } else if (mTvGravity.getText().toString().equals("0.00") || mTvGravity.getText().toString().equals("0.0")) {
                    Toast.makeText(this, "收集重量不能为0！", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = getIntent();
                    String qrCode = intent.getStringExtra("scan_result");
                    collectMap.put("departQrCode", qrCode);
                    collectMap.put("remark", mRemark.getText().toString());
                    collectMap.put("weight", mTvGravity.getText().toString());
                    if (StringUtil.isNotEmpty(mRfidCode.getText().toString())) {
                        collectMap.put("rfid", mRfidCode.getText().toString());
                    }
                    Paper.book().write(Constants.COLLECTMAP, collectMap);
                    Intent intent2 = new Intent(WasteCollectActivity.this, HandoverScanActivity.class);
                    startActivity(intent2);
                    finish();
                }
                break;
            case R.id.read:     //RFID读取按钮
                epcSet.clear();
                isLoop = true;
                if (MainApplication.mService != null) {
                    LoopReadEPC();
                } else {
                    Toast.makeText(WasteCollectActivity.this, "此设备暂不支持RFID扫描！", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 开启语音识别对话框，将说的话转成文字
     */
    private void speechToText() {
        setParam();
        // 显示听写对话框
        mIatDialog.setListener(mRecognizerDialogListener);
        mIatDialog.show();
        TextView txt = mIatDialog.getWindow().getDecorView().findViewWithTag("textlink");
        txt.setText("");
        txt.getPaint().setFlags(Paint.SUBPIXEL_TEXT_FLAG);//取消下划线
        txt.setEnabled(false);
        Toast.makeText(WasteCollectActivity.this, "请开始说话...", Toast.LENGTH_SHORT).show();
    }

    /**
     * 开启通知并监听接收蓝牙数据
     */
    private void receiveBleData() {
        if (StringUtil.isNotEmpty(uuid_service) && StringUtil.isNotEmpty(uuid_character)) {
            BleManager.getInstance().notify(Constants.BLEDEVICE, uuid_service, uuid_character, new BleNotifyCallback() {
                @Override
                public void onNotifySuccess() {
                    Log.i("打开通知", "操作成功！");
                }

                @Override
                public void onNotifyFailure(BleException exception) {
                    Log.i("打开通知", "操作失败！");
                }

                @Override
                public void onCharacteristicChanged(byte[] data) {
                    //打开通知后，设备发过来的数据将在这里出现
                    if (data != null && data.length > 0) {
                        StringBuilder stringBuilder = new StringBuilder(data.length);

                        for (byte byteChar : data) {
                            stringBuilder.append(String.format("%02X ", byteChar));
                        }
                        Log.i("重量", new String(data) + "\n");
                        gravity = new String(data);
                    }
                }
            });
        }
    }

    /**
     * 开启循环扫描RFID
     */
    public void LoopReadEPC() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isLoop) {
                    uhf_6c.inventory(callback);
                    if (!isLoop) {
                        break;
                    }
                    try {
                        Thread.sleep(150);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;

                    }
                }
            }
        });
        thread.start();
    }

    IUhfCallback callback = new IUhfCallback.Stub() {
        @Override
        public void doInventory(List<String> str) throws RemoteException {
            Log.d("Merlin", "count=" + str.size());

            for (int i = 0; i < str.size(); i++) {
                String strepc = str.get(i);
                Log.d("Merlin", "RSSI=" + strepc.substring(0, 2));
                Log.d("Merlin", "PC=" + strepc.substring(2, 6));
                Log.d("Merlin", "EPC=" + strepc.substring(6));
                DevBeep.PlayOK();
                String strEpc = strepc.substring(2, 6) + strepc.substring(6);
                epcSet.add(strEpc);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = strepc.substring(6);
                mHandler.sendMessage(msg);
            }
        }

        @Override
        public void doTIDAndEPC(List<String> str) throws RemoteException {
            for (Iterator it2 = str.iterator(); it2.hasNext(); ) {
                String strepc = (String) it2.next();
                int nlen = Integer.valueOf(strepc.substring(0, 2), 16);
            }
        }
    };

    @SuppressLint("HandlerLeak")
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String epc = (String) msg.obj;
                if (epcSet.size() > 0) {
                    isLoop = false;
                    mRfidCode.setText(epc);
                }
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isLoop = false;
    }
}